#include "mainwindow.h"
#include "ui_mainwindow.h"

const QString& SERVER_IP="127.0.0.1";
const quint16 SERVER_PORT=9090;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端");
    socket = new QUdpSocket(this);
    //通过信号槽处理服务器返回数据
    connect(socket,&QUdpSocket::readyRead,this,[this](){
        //读取响应数据
        const QNetworkDatagram& responseDatagram=socket->receiveDatagram();
        QString response=responseDatagram.data();
        //将数据显示到列表框上
        ui->listWidget->addItem("服务器说: "+response);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    //获取输入框内容
    const QString& text=ui->lineEdit->text();
    //构造请求数据
    QNetworkDatagram requestDatagram(text.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);
    //发送请求数据
    socket->writeDatagram(requestDatagram);
    //把发送的请求也添加到列表框中
    ui->listWidget->addItem("客户端说: "+text);
    //把输入框内容清空
    ui->lineEdit->setText("");
}
